#import "FlutterAlibcPlugin.h"
#import "ALiTradeSDKShareParam.h"

#import <AlibcTradeSDK/AlibcTradeSDK.h>
#import <AlibcTradeSDK/AlibcTradeService.h>
#import <AlibcTradeSDK/AlibcTradePageFactory.h>
#import <AlibcTradeSDK/AlibcTradeSDK.h>
#import <AlibcTradeSDK/AlibcTradeService.h>
#import <AlibcTradeSDK/AlibcTradePageFactory.h>


@implementation FlutterAlibcPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"flutter_alibc"
            binaryMessenger:[registrar messenger]];
  FlutterAlibcPlugin* instance = [[FlutterAlibcPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"initSdk" isEqualToString:call.method]) {
    BOOL debug = call.arguments[@"debug"];
    [self initSdk:debug :result];
  } else if ([@"login" isEqualToString:call.method]){
      [self login:result];
  } else if ([@"loginout" isEqualToString:call.method]){
      [[ALBBSDK sharedInstance] logout];
      result(@YES);
  } else if ([@"openByUrl" isEqualToString:call.method]){
      NSString *url = call.arguments[@"url"];
      NSString *pid = call.arguments[@"pid"];
      NSString *adzoneid = call.arguments[@"adzoneid"];
      NSString *taokeAppkey = call.arguments[@"taokeAppkey"];
      NSString *sellerId = call.arguments[@"sellerId"];
      [self openPageByNewWay:url :pid :adzoneid :taokeAppkey :sellerId];
      result(NULL);
  } else if ([@"getLoginSession" isEqualToString:call.method]){
      ALBBUser * user = [[ALBBCompatibleSession sharedInstance] getUser];
      NSData * jsonData = [NSJSONSerialization dataWithJSONObject:user options:NSJSONWritingPrettyPrinted error:nil];
      NSString * json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
      result(json);
  } else {
    result(FlutterMethodNotImplemented);
  }
}
- (void)initSdk:(BOOL) debug :(FlutterResult)result {
    // 百川平台基础SDK初始化，加载并初始化各个业务能力插件
    [[AlibcTradeSDK sharedInstance] setDebugLogOpen:debug];//开发阶段打开日志开关，方便排查错误信息
//    [[AlibcTradeSDK sharedInstance] setIsvVersion:@"2.2.2"];
//    [[AlibcTradeSDK sharedInstance] setIsvAppName:@"baichuanDemo"];
    
    [[AlibcTradeSDK sharedInstance] asyncInitWithSuccess:^{
        NSDictionary * dict = @{@"message":@"百川SDK初始化成功", @"isSuccess":@YES};
        NSData * jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
        NSString * json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        result(json);
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
        NSDictionary * dict = @{@"message":@"百川SDK初始化失败", @"isSuccess":@NO};
        NSData * jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
        NSString * json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        result(json);
    }];
   
}
- (void)login:(FlutterResult)result {
    if(![[ALBBCompatibleSession sharedInstance] isLogin]) {
        [[ALBBSDK sharedInstance] setH5Only:NO];
        [[ALBBSDK sharedInstance] auth:self successCallback:^{
            ALBBUser * user = [[ALBBCompatibleSession sharedInstance] getUser];
            NSData * jsonData = [NSJSONSerialization dataWithJSONObject:user options:NSJSONWritingPrettyPrinted error:nil];
            NSString * json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            result(json);
        } failureCallback:^(NSError *error) {
            NSLog(@"%@", error);
            result(NULL);
        }];
     
    } else {
        ALBBUser * user = [[ALBBCompatibleSession sharedInstance] getUser];
        NSData * jsonData = [NSJSONSerialization dataWithJSONObject:user options:NSJSONWritingPrettyPrinted error:nil];
        NSString * json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        result(json);
    }
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation{
    // 如果百川处理过会返回YES
    if (![[AlibcTradeSDK sharedInstance] application:application
                                             openURL:url
                                   sourceApplication:sourceApplication
                                          annotation:annotation]) {
        // 处理其他app跳转到自己的app
    }
    return YES;
}

//IOS9.0 系统新的处理openURL 的API
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<NSString *,id> *)options {
     
    if (@available(iOS 9.0, *)) {
        __unused BOOL isHandledByALBBSDK=[[AlibcTradeSDK sharedInstance]
                                          application:application
                                          openURL:url
                                          options:options];
    } else {
        // Fallback on earlier versions
    }//处理其他app跳转到自己的app，如果百川处理过会返回YES
     
    return YES;
}
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts {
    [URLContexts enumerateObjectsUsingBlock:^(UIOpenURLContext * _Nonnull obj,
                                              BOOL * _Nonnull stop) {
        if([[AlibcTradeSDK sharedInstance] application:nil
                                               openURL:obj.URL
                                               options:nil]){
            *stop = YES;
        }
    }];
}

- (void)openPageByNewWay:(NSString *)url: (NSString *)pid: (NSString *)adzoneid: (NSString *)taokeAppkey: (NSString *)sellerId {
    AlibcTradeShowParams* showParam = [[AlibcTradeShowParams alloc] init];
    showParam.openType = AlibcOpenTypeAuto;
    showParam.isNeedCustomNativeFailMode = [ALiTradeSDKShareParam sharedInstance].isNeedCustomFailMode;
//        showParam.backUrl=@"tbopen23082328:https://h5.m.taobao.com";
    BOOL isNeedPush=[ALiTradeSDKShareParam sharedInstance].isNeedPush;
    showParam.isNeedPush=isNeedPush;
    showParam.nativeFailMode=AlibcNativeFailModeJumpH5;
    showParam.linkKey=@"taobao";
    showParam.degradeUrl = [ALiTradeSDKShareParam sharedInstance].degardeUrl;
    
    AlibcTradeTaokeParams *taokeParam = [[AlibcTradeTaokeParams alloc] init];
    taokeParam.adzoneId = adzoneid;
    taokeParam.pid = pid;
    taokeParam.extParams = [[NSMutableDictionary alloc]initWithObjectsAndKeys:sellerId, @"sellerId",taokeAppkey,@"taokeAppkey", nil];
//    NSString *extParams = [NSString stringWithFormat:@"{\"sellerId\":%@,\"taokeAppkey\":%@}",sellerId,taokeAppkey];
//    NSMutableDictionary *taokeParam = [[NSMutableDictionary alloc]initWithObjectsAndKeys:pid, @"pid"
////                                       ,adzoneid,@"unionId",@"mm_10011550_0_0", @"subPid",
//                                       ,adzoneid,@"adzoneId",extParams,@"extParams",nil];
    
//    NSMutableDictionary *customParam = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"mm_100713040_22792955_75330474", @"pid",@"",@"unionId",@"mm_10011550_0_0", @"subPid", @"29932014",@"adzoneId",@"{\"sellerId\":2241885069,\"taokeAppkey\":23281718}",@"extParams",nil];

    [[AlibcTradeSDK sharedInstance].tradeService openByUrl:url identity:@"trade" webView:nil parentController:self showParams:showParam taoKeParams:taokeParam trackParam:NULL tradeProcessSuccessCallback:^(AlibcTradeResult *tradeProcessResult){
        if(tradeProcessResult.result ==AlibcTradeResultTypePaySuccess){
            NSString *tip=[NSString stringWithFormat:@"交易成功:成功的订单%@\n，失败的订单%@\n",[tradeProcessResult payResult].paySuccessOrders,[tradeProcessResult payResult].payFailedOrders];
            NSLog(@"%@",tip);
        }else if(tradeProcessResult.result==AlibcTradeResultTypeAddCard){
        }
    } tradeProcessFailedCallback:^(NSError *error){
        //        退出交易流程
                if (error.code==AlibcErrorCancelled) {
                    return ;
                }
                NSDictionary *infor=[error userInfo];
                NSArray*  orderid=[infor objectForKey:@"orderIdList"];
                NSString *tip=[NSString stringWithFormat:@"交易失败:\n订单号\n%@",orderid];
                NSLog(@"%@",tip);
            }];
//    if(isNeedPush){
//        NSInteger res  =  [[AlibcTradeSDK sharedInstance].tradeService openByUrl:url identity:@"trade" webView:nil parentController:self.navigationController showParams:showParam taoKeParams:[self taokeParam] trackParam:[self customParam] tradeProcessSuccessCallback:self.onTradeSuccess tradeProcessFailedCallback:self.onTradeFailure];
//
//        if (res == 1) {
//
//        }
//    }else {
//
//    }
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

//- (void)OpenPageByNewWay:(id<AlibcTradePage>)page BizCode:(NSString *)bizCode{
//    AlibcTradeShowParams* showParam = [[AlibcTradeShowParams alloc] init];
//    showParam.openType = [self openType];
//    //    showParam.backUrl=@"tbopen23082328:https://h5.m.taobao.com";
//    BOOL isNeedPush=[ALiTradeSDKShareParam sharedInstance].isNeedPush;
//    BOOL isBindWebview=[ALiTradeSDKShareParam sharedInstance].isBindWebview;
//    showParam.isNeedPush=isNeedPush;
//    showParam.nativeFailMode=[self NativeFailMode];
//    showParam.isNeedCustomNativeFailMode = [ALiTradeSDKShareParam sharedInstance].isNeedCustomFailMode;
//    showParam.linkKey=[self schemeType];
//    showParam.degradeUrl = [ALiTradeSDKShareParam sharedInstance].degardeUrl;
//    if (isBindWebview) {
//        ALiTradeWebViewController* view = [[ALiTradeWebViewController alloc] init];
//        NSInteger res  =  [[AlibcTradeSDK sharedInstance].tradeService openByBizCode:bizCode page:page webView:view.webView parentController:view showParams:showParam taoKeParams:[self taokeParam] trackParam:[self customParam] tradeProcessSuccessCallback:self.onTradeSuccess tradeProcessFailedCallback:self.onTradeFailure];
//        if (res == 1) {
//            [self.navigationController pushViewController:view animated:YES];
//        }
//    } else {
//        if (isNeedPush) {
//             [[AlibcTradeSDK sharedInstance].tradeService openByBizCode:bizCode page:page webView:nil parentController:self.navigationController showParams:showParam taoKeParams:[self taokeParam] trackParam:[self customParam] tradeProcessSuccessCallback:self.onTradeSuccess tradeProcessFailedCallback:self.onTradeFailure];
//
//        } else {
//             [[AlibcTradeSDK sharedInstance].tradeService openByBizCode:bizCode page:page webView:nil parentController:self showParams:showParam taoKeParams:[self taokeParam] trackParam:[self customParam] tradeProcessSuccessCallback:self.onTradeSuccess tradeProcessFailedCallback:self.onTradeFailure];
//
//        }
//
//    }
//}

@end
